package com.cat.slidingWindow;

import java.util.HashMap;

/**
 * @author cat
 * @description https://leetcode.cn/problems/fruit-into-baskets/description/
 * @create 2025/7/29 10:40
 * @since JDK17
 */

public class Solution07 {
    static HashMap<Integer, Integer> map = new HashMap<>();

    public int totalFruit(int[] fruits) {
        int cnt = 0, ans = 0, n = fruits.length, total;
        for (int l = 0, r = 0; r < n; r++) {
            total = map.getOrDefault(fruits[r], 0);
            cnt += total == 0 ? 1 : 0; // 新增了一个种类
            map.put(fruits[r], total + 1);
            while (cnt > 2) { // 种类
                total = map.get(fruits[l]); // 获取l位置有多少个
                if (total == 1) {
                    cnt--;
                }
                map.put(fruits[l++], total - 1);
            }
            ans = Math.max(ans, r - l + 1);
        }
        map.clear();
        return ans;
    }
}
